package com.rzico.sbl.ui.manager

import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMasterInfoBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.other.showShopDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeByFinally
import kotlin.text.orEmpty

class MasterInfoActivity : BaseActivity(R.layout.activity_master_info) {

    private val mBinding by lazy { ActivityMasterInfoBinding.bind(getRootView()) }

    private val mShopList = ArrayList<MasterData>()
    private var mItemId = ""
    private var mShopId = ""
    private var mRoleId = ""
    private var mRoleStatus = ""

    override fun getViewModel() = get<MasterViewModel>()

    override fun initData() {
        initTitle(title = "员工管理")

        initDisplay(intent.getParcelableExtra("data"))
    }

    override fun initListener() {
        mBinding.apply {
            infoName.filters = arrayOf(NameLengthFilter(20))

            (userRole !in "1,2")
                .condition {
                    infoName.isEnabled = false
                    infoNameEdit.gone()
                    infoBottom.gone()
                }

            infoJobLl.oneClick {
                if (userRole in "1,2") {
                    when (mRoleId) {
                        "-1" -> {
                            showToast("暂不能修改店主职位")
                            return@oneClick
                        }
                        // mRoleList.isEmpty() -> getRoleList { showRoleDialog() }
                        else -> showRoleDialog()
                    }
                } else
                    showToast("暂无权限修改，请联系店长或管理员")
            }

            infoShopLl.oneClick {
                if (userRole in "1,2") {
                    if (mShopList.isEmpty())
                        getShopList { showShopDialog() }
                    else showShopDialog()
                } else
                    showToast("暂无权限修改，请联系店长或管理员")
            }

            infoStatusLl.oneClick {
                (userRole in "1,2")
                    .condition {
                        showListDialog(
                            title = "工作状态",
                            items = listOf("工作中", "休息中", "已离职"),
                            listener = { index, hint ->
                                mRoleStatus = when (index) {
                                    1 -> "rest"
                                    2 -> "quit"
                                    else -> "normal"
                                }

                                infoStatus.text = hint
                            }
                        )
                    }
            }

            infoArea.oneClick { startActivityEx<MasterAreaActivity>() }
            infoNamed.oneClick {
                startActivityEx<MasterTransferActivity>(
                    "masterId" to mItemId
                )
            }

            btSave.oneClick {
                when {
                    mRoleId.isEmpty() -> {
                        showToast("请选择职位")
                        return@oneClick
                    }

                    infoName.textTrim.isEmpty() -> {
                        showToast("请输入员工姓名")
                        mBinding.infoName.requestFocus()
                        return@oneClick
                    }

                    mShopId.isEmpty() -> {
                        showToast("请设置所在店铺")
                        return@oneClick
                    }
                }

                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngUpdate,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mItemId,
                            "name" to infoName.textTrim,
                            "roleId" to if (mRoleId == "-1") "" else mRoleId,
                            "shopId" to mShopId,
                            "workStatus" to mRoleStatus
                        ),
                        onSuccess = {
                            showToast("信息修改成功！")

                            // 更新员工列表
                            LiveEventBus
                                .get("masterList")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    private fun initDisplay(bean: MasterData?) {
        bean?.let {
            mItemId = it.id
            mShopId = it.shopId.orEmpty()
            mRoleId = when (it.roleName) {
                "店主" -> "-1"
                else -> it.roleId
            }
            mRoleStatus = it.status.orEmpty("normal")

            mBinding.apply {
                infoJob.text = it.roleName
                infoName.setText(it.name)
                infoName.setSelection(infoName.text.length)
                infoPhone.text = it.mobile
                infoShop.text = it.shopName
                infoStatus.text = when (mRoleStatus) {
                    "rest" -> "休息中"
                    "quit" -> "已离职"
                    else -> "工作中"
                }
                infoCount.text = it.shippingCard
                infoImg.loadCircleImage(it.logo, R.mipmap.default_user)
                infoName.requestFocus()

                infoOrderLl.isVisible = it.roleId in "1,2,3,10"
            }
        }
    }

    /**
     * 显示角色弹框
     */
    private fun showRoleDialog() {
        val roleList = getViewModel()
            .mRoleList
            .filter { userRole in it.hint }

        showListDialog(
            title = "请选择职位",
            index = roleList.indexOfFirst { it.id == mRoleId },
            items = roleList.map { it.name },
            listener = { index, hint ->
                mRoleId = roleList[index].id
                mBinding.infoJob.text = hint
            }
        )
    }

    /**
     * 显示店铺弹框
     */
    private fun showShopDialog() {
        showShopDialog(mShopList) {
            mShopId = mShopList[it].id
            mBinding.infoShop.text = mShopList[it].name
        }
    }

    /**
     * 角色列表
     */
    private fun getRoleList(onFinish: () -> Unit) {
        getViewModel()
            .requestCommon(
                isLoading = true,
                requestUrl = BaseUrl.mngRole,
                requestMethod = HttpMethod.GET,
                onSuccess = {
                    // mRoleList.addItems(it)

                    onFinish.invoke()
                }
            )
    }

    /**
     * 店铺列表
     */
    private fun getShopList(onFinish: () -> Unit) {
        getViewModel()
            .masterShop()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mShopList.addItems(list)

                    if (mShopList.any { it.id == mShopId }) {
                        mShopList.find { it.id == mShopId }?.check = true
                    }

                    onFinish.invoke()
                }
            )
    }

}